<template>
  <el-dialog
    :visible="dialogVisible"
    :close-on-click-modal="false"
    :title="dialogTitle"
    append-to-body
    width="800px"
    @close="handleCancel">

    <div class="scene-create">
      <div class="scene-title">
        <div class="scene-title__name">场景名称</div>
        <el-input
          v-model.trim="sceneForm.name"
          :maxlength="10"
          class="scene-title__input"
          placeholder="请输入场景名称，最多10个字符"/>
      </div>

      <form-content
        v-if="showFilter"
        ref="formContent"
        :id="id"
        :default-value="defaultValue"
        :field-list="fieldList"
        class="filter-container" />

      <div class="save-setting">
        <el-checkbox
          v-model="sceneForm.defaultScene"
          :true-label="1"
          :false-label="0">
          设置为默认
        </el-checkbox>
      </div>
    </div>

    <div slot="footer">
      <el-button
        @click="handleCancel">
        取 消
      </el-button>
      <el-button
        type="primary"
        @click="handleConfirm">
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { jxcFieldSceneQueryFieldAPI } from '@/api/jxc/field'
import { jxcSceneAddAPI, jxcSceneQueryByIdAPI } from '@/api/jxc/scene'

import FormContent from '../WkAdvancedFilter/FormContent'
import jxcTypes from '../../jxcTypes'
import { isEmpty, isArray } from '@/utils/types'
import jxcExamineLib from '../../jxcExamineStatus'

export default {
  name: 'SceneCreate',
  components: {
    FormContent
  },
  props: {
    id: {
      type: [String, Number],
      default: null
    },
    // 进销存类型
    type: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      dialogVisible: true,
      loading: false,

      sceneForm: {
        name: '', // 场景名称
        isDefault: 0,
        defaultScene: 0 // 是否设置为默认场景
      },

      defaultValue: [],
      fieldList: [],
      showFilter: false
    }
  },
  computed: {
    dialogTitle() {
      return this.id ? '编辑场景' : '新建场景'
    },
    typeObj() {
      return jxcTypes[this.type]
    }
  },
  created() {
    this.getFilterFieldInfo()
  },
  methods: {
    /**
     * 查询高级筛选字段
     */
    getFilterFieldInfo() {
      const reqArr = [
        jxcFieldSceneQueryFieldAPI({
          label: this.typeObj.label
        })
      ]
      if (this.id) {
        reqArr.push(
          jxcSceneQueryByIdAPI({
            sceneId: this.id
          })
        )
      }
      Promise.all(reqArr).then(resArr => {
        console.log('resArr', resArr)

        resArr[0].data.forEach(item => {
          if (item.fieldName === 'product_ishelf') {
            item.setting = [
              { label: '上架', value: 1 },
              { label: '下架', value: 0 }
            ]
          } else if (item.formType === 'state_cause') {
            item.setting = []
            jxcExamineLib.forEach(o => {
              if (this.type === 'jxc_receipt') {
                if ([5, 6].includes(o.jxc_state)) {
                  item.setting.push({
                    label: o.label,
                    value: o.jxc_state
                  })
                }
              } else if (this.type === 'jxc_outbound') {
                if ([4, 6].includes(o.jxc_state)) {
                  item.setting.push({
                    label: o.label,
                    value: o.jxc_state
                  })
                }
              } else if (![0, 1, 4, 5].includes(o.jxc_state)) {
                item.setting.push({
                  label: o.label,
                  value: o.jxc_state
                })
              }
            })
          }
        })
        this.fieldList = resArr[0].data

        if (resArr.length > 1) {
          this.sceneForm = {
            name: resArr[1].data.name,
            defaultScene: resArr[1].data.defaultScene,
            isDefault: resArr[1].data.isDefault
          }
          // this.formatDefaultValue(resArr[1].data.searchList)
          this.defaultValue = resArr[1].data.searchList
          this.showFilter = true
        } else {
          this.showFilter = true
        }
      }).catch(() => {})
    },

    // formatDefaultValue(list) {
    //   this.defaultValue = list
    //   console.log('default list: ', list)
    // },

    handleCancel() {
      this.$emit('close')
    },

    handleConfirm() {
      if (this.loading) return
      if (!this.showFilter) {
        this.handleCancel()
        return
      }
      if (isEmpty(this.sceneForm.name)) {
        this.$message.error('场景名称不能为空！')
        return
      }
      const list = this.$refs.formContent.getValue()
      if (!list) return

      const params = {
        ...this.sceneForm,
        searchList: list.map(o => {
          return {
            formType: o.formType,
            name: o.fieldName,
            type: o.conditionVal,
            values: this.getFilterValue(o.value, o.formType)
          }
        }),
        type: this.typeObj.label
      }
      if (this.id) {
        params.sceneId = this.id
      }
      console.log('save as scene: ', params)

      this.loading = true
      jxcSceneAddAPI(params).then(() => {
        this.loading = false
        this.$emit('update')
        this.handleCancel()
      }).catch(() => {
        this.loading = false
      })
    },

    /**
     * 获取条件对应的值
     * @param val
     * @param formType
     * @returns {*[]|*}
     */
    getFilterValue(val, formType) {
      if (!val) return []
      return isArray(val) ? val : [val]
    }
  }
}
</script>

<style scoped lang="scss">
/deep/ .el-dialog__body {
  padding: 10px 20px;
}

.scene-create {
  .scene-title {
    padding-bottom: 15px;
    .scene-title__name {
      margin-bottom: 10px;
    }
    .scene-title__input {
      width: 300px;
    }
  }

  .el-form {
    max-height: 200px;
    overflow-y: auto;
    .el-form-item {
      margin-bottom: 0;
    }
  }

  .save-setting {
    margin-top: 20px;
  }
}
</style>
